package cn.itsource.org.controller;

import cn.itsource.org.domain.Department;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import cn.itsource.utli.AjaxResult;
import cn.itsource.utli.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/department")
@Api(tags = "部门接口",description = "部门接口详细描述")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    /**
     *查找错you
     * @return
     */
    @GetMapping
    public List<Department> getAll(){
        return  departmentService.queryAll();
    }

    /**
     * 新增和修改
     * @param department
     * @return
     */
    @PutMapping
    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult saveOrUpdate(@RequestBody Department department){
        try {
            if (department.getId()==null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }

    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }

    }

    /**
     * 根据id查找
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
        return departmentService.queryById(id);
    }

    @PostMapping
    public PageInfo<Department> page( @RequestBody DepartmentQuery query){
        return  departmentService.queryPage(query);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody Long[] ids){
        try {
            System.out.println(Arrays.toString(ids));
            //删除所有id
            departmentService.patchDel(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }

    }

    /**
     * 获取部门树
     * @return
     */
    @GetMapping("/deptTree")
    public List<Department> getDeptTree(){
        return departmentService.getDeptTree();
    }


}
